package com.ruoyi.print.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.print.config.AliyunConfig;
import com.ruoyi.print.service.IImageSegService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片分割服务实现类
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@Service
public class ImageSegServiceImpl implements IImageSegService {
    
    private static final Logger log = LoggerFactory.getLogger(ImageSegServiceImpl.class);
    
    @Autowired
    @Qualifier("printAliyunConfig")
    private AliyunConfig aliyunConfig;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    public static com.aliyun.imageseg20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        /*
          初始化配置对象com.aliyun.teaopenapi.models.Config
          Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
         */
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imageseg20191230.Client(config);
    }

    // ... existing code ...
    @Override
    public String segmentImage(String imageUrl) {
    try {

        com.aliyun.imageseg20191230.Client client = ImageSegServiceImpl.createClient(aliyunConfig.getImageseg().getAccessKeyId(), aliyunConfig.getImageseg().getAccessKeySecret());
        // 构造请求
        com.aliyun.imageseg20191230.models.SegmentCommonImageRequest request = new com.aliyun.imageseg20191230.models.SegmentCommonImageRequest()
                .setImageURL(imageUrl);
        log.debug(request.toString());
        // 执行请求
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.imageseg20191230.models.SegmentCommonImageResponse response = client.segmentCommonImageWithOptions(request, runtime);
        log.debug(response.toString());
        // 返回分割后的图片 URL
        return response.getBody().getData().getImageURL();
    } catch (Exception e) {
        log.error("图片分割失败", e);
        return null;
    }
}
// ... existing code ...

} 